<template>
  <div class="app-container">
    <!-- 表格 -->
    <vxe-grid ref="xGridDom" v-bind="xGridOpt">
      <!-- 左侧按钮列表 -->
      <template #toolbar-btns>
        <vxe-button status="primary" icon="vxe-icon-add" @click="crudStore.onShowModal()">新增客户</vxe-button>
      </template>

      <!--      展开行的内容-->
      <!--      <template #expand-content="{ row }">-->
      <!--        <div class="expand-wrapper">-->
      <!--          <ul>-->
      <!--            <li style="list-style-type: none;">-->
      <!--              <span>备注: {{ row.description }}</span>-->
      <!--            </li>-->
      <!--          </ul>-->
      <!--        </div>-->
      <!--      </template>-->

      <template #row-name="{ row }">
        <div>
          <template v-if="row.description">
            <el-tooltip class="box-item" effect="dark" placement="right">
              <template #content>
                <div class="tooltip-content">
                  {{ row.description }}
                </div>
              </template>
              {{ row.name }}
            </el-tooltip>
          </template>
          <template v-else>
            {{ row.name }}
          </template>
        </div>
      </template>

      <!-- 操作 -->
      <template #row-operate="{ row }">
        <el-tooltip class="box-item" effect="dark" content="查看环境" placement="top-end">
          <el-button link icon="Position" type="primary" @click="toEnv(row.name)"/>
        </el-tooltip>
        <el-divider direction="vertical" />
        <el-tooltip class="box-item" effect="dark" content="编辑" placement="top-end">
          <el-button link icon="Edit" type="primary" @click="crudStore.onShowModal(row)"/>
        </el-tooltip>
        <el-divider direction="vertical" />
        <el-tooltip class="box-item" effect="dark" content="删除" placement="top-end">
          <el-button link icon="Delete" type="danger" @click="crudStore.onDelete(row)"/>
        </el-tooltip>
      </template>


    </vxe-grid>
    <!-- 弹窗 -->
    <vxe-modal ref="xModalDom" v-bind="xModalOpt">
      <!-- 表单 -->
      <vxe-form ref="xFormDom" v-bind="xFormOpt"></vxe-form>
    </vxe-modal>
  </div>
</template>

<script lang="ts" setup>
import {computed, nextTick, reactive, ref, Ref} from "vue"
import {type ElMessageBoxOptions, ElMessageBox, ElMessage} from "element-plus"
import StatusColumnSolts from "./tsx/StatusColumnSolts"
import {formatDate, formatDateTime, trimValue} from "@/utils/index"

import {
  type VxeGridInstance,
  type VxeGridProps,
  type VxeModalInstance,
  type VxeModalProps,
  type VxeFormInstance,
  type VxeFormProps,
  type VxeGridPropTypes,
  type VxeFormDefines
} from "vxe-table"

import {
  addCustomerApi,
  updateCustomerApi,
  deleteCustomerApi,
  getCustomerApi,
  RowMeta,
  CustomerTableData, importCustomer, selectOption
} from "@/api/customer"
import TypeColumnSolts from "@/views/customer/list/tsx/TypeColumnSolts"
import {result} from "lodash-es";
import {useRouter} from "vue-router";
import {getAllPeople} from "@/utils/customer";

defineOptions({
  name: "Customer"
})


const router = useRouter()

const toEnv = (name: string) => {
  router.push({
    path: "/customer/env",
    query: {
      name
    }
  })
}

const peopleOptions = ref<selectOption[]>([])
getAllPeople().then((Options) => {
  if (Options) {
    peopleOptions.value = Options || []
  }
})

//#region vxe-grid
const xGridDom = ref<VxeGridInstance>()


const xGridOpt: VxeGridProps = reactive({
  loading: true,
  autoResize: true,
  exportConfig: {
    types: ['csv'], // 导出的文件类型
    isHeader: true, // 是否包含表头
    isFooter: true, // 是否包含表尾
    isColgroup: true, // 是否包含列分组
    isMerge: true, // 是否合并单元格
    modes: ["current", "all"],      // ["current", "selected", "all"]
    beforeExportMethod: ({options}) => {
      // 想在导出前对数据做些处理，但打印不出来options.data，先放弃吧
      // TMD，在queryAll方法里处理不就得了，非得在这处理？我真蠢
      // console.log(options)
    }
  },
  importConfig: {
    modes: ['insert', 'covering'], // 导入的模式
    types: ['csv'], // 允许导入的文件类型
    remote: true,      // 是否为服务端导入
    importMethod: ({file, options}) => {
      return new Promise<any>((resolve: Function) => {
        const formData = new FormData()
        formData.append("file", file)

        /** 加载数据 */
        const callback = (res: any) => {
          if (res && res.data) {
            ElMessage({type: "success", message: res.msg})
          }
          xGridOpt.loading = false
          xGridDom.value?.commitProxy("query")
          resolve(result)
        }

        const params = {
          mode: options.mode,
          type: options.type
        }
        importCustomer(formData, params).then(callback).catch(callback)
      })
    }
  },
  /** 展开行 */
  // expandConfig: {
  //   iconColumnIndex: 0, // 展开图标所在的列索引
  //   expandAll: false, // 是否默认展开所有行
  //   expandRowKeys: [], // 默认展开的行的 key
  //   accordion: false, // 是否每次只能展开一行
  //   iconClose: "vxe-icon-add",
  //   iconOpen: "vxe-icon-minus",
  // },
  /** 分页配置项 */
  pagerConfig: {
    align: "right"
  },
  /** 表单配置项 */
  formConfig: {
    items: [
      {
        field: "name",
        itemRender: {
          name: "$input",
          props: {placeholder: "客户名称", clearable: true}
        }
      },
      {
        field: "businessName",
        itemRender: {
          name: "$input",
          props: {placeholder: "商务名称", clearable: true}
        }
      },
      {
        field: "type",
        itemRender: {
          name: "$select",
          props: {placeholder: "选择客户类型", clearable: true},
          options: [
            {value: "1", label: "POC客户"},
            {value: "2", label: "正式客户"}
          ]
        }
      },
      {
        field: "vipLevel",
        itemRender: {
          name: "$select",
          props: {placeholder: "选择客户等级", clearable: true},
          options: [
            {value: 1, label: "VIP 1"},
            {value: 2, label: "VIP 2"},
            {value: 3, label: "VIP 3"},
            {value: 4, label: "VIP 4"},
            {value: 10, label: "未知"}
          ]
        }
      },
      {
        field: "serviceStatus",
        itemRender: {
          name: "$select",
          props: {placeholder: "选择维保状态", clearable: true},
          options: [
            {label: "已过期", value: 2},
            {label: "维保中", value: 1}
          ]
        }
      },
      {
        field: "maintenanceType",
        itemRender: {
          name: "$select",
          props: {placeholder: "选择维保类型", clearable: true},
          options: [
            {label: "付费", value: 1},
            {label: "免费", value: 2},
            {label: "未知", value: 10}
          ]
        }
      },
      {
        itemRender: {
          name: "$buttons",
          children: [
            {
              props: {type: "submit", content: "搜索", status: "primary"}
            }
          ]
        }
      }
    ]
  },
  /** 工具栏配置 */
  toolbarConfig: {
    refresh: true,
    custom: false,
    export: true,
    import: true,
    slots: {
      buttons: "toolbar-btns"
    }
  },
  /** 列配置 */
  columns: [
    // {
    //   type: 'expand', // 设置列类型为展开列
    //   width: 30, // 设置展开列的宽度
    //   slots: {content: "expand-content"}
    // },
    {
      field: "id",
      title: "ID",
      width: "100px"
    },
    {
      field: "name",
      title: "客户名称",
      slots: {default: "row-name"}
    },
    {
      field: "type",
      title: "客户类型",
      slots: TypeColumnSolts
    },
    {
      field: "vipLevel",
      title: "客户等级",
      formatter: (params) => {
        let value = "N/A"
        if (params.row.vipLevel !== 10) {
          value = `VIP ${params.row.vipLevel} `
        }
        return value
      }
    },
    {
      field: "serviceStatus",
      title: "维保状态",
      slots: StatusColumnSolts
    },
    {
      field: "maintenanceType",
      title: "维保类型",
      formatter: (params) => {
        let value = "N/A"
        if (params.row.maintenanceType === 1) {
          value = "付费"
        } else if (params.row.maintenanceType === 2) {
          value = "免费"
        }
        return value
      }
    },
    {
      field: "businessName",
      title: "商务",
      formatter: (params) => {
        return params.row.businessName === "" ? "N/A" : params.row.businessName
      }
    },
    {
      field: "serviceStartDate",
      title: "维保起始日期",
      formatter: (params) => {
        return formatDate(params.row.serviceStartDate)
      }
    },
    {
      field: "serviceEndDate",
      title: "维保截止日期",
      formatter: (params) => {
        return formatDate(params.row.serviceEndDate)
      }
    },
    {
      field: "updatedAt",
      sortable: true,
      title: "更新时间",
      formatter: (params) => {
        return formatDateTime(params.row.updatedAt)
      }
    },
    {
      title: "操作",
      width: "250px",
      fixed: "right",
      showOverflow: false,
      slots: {default: "row-operate"}
    }
  ],
  /** 数据代理配置项（基于 Promise API） */
  proxyConfig: {
    /** 启用动态序号代理 */
    seq: true,
    /** 是否代理表单 */
    form: true,
    /** 是否自动加载，默认为 true */
    // autoLoad: false,
    props: {
      total: "total"
    },
    ajax: {
      query: ({page, form}: VxeGridPropTypes.ProxyAjaxQueryParams) => {
        xGridOpt.loading = true
        crudStore.clearTable()
        return new Promise<any>((resolve: Function) => {
          let total = 0
          let result: RowMeta[] = []
          /** 加载数据 */
          const callback = (res: CustomerTableData) => {
            if (res && res.data) {
              const resData = res.data
              // 总数
              if (Number.isInteger(resData.total)) {
                total = resData.total
              }
              // 分页数据
              if (Array.isArray(resData.list)) {
                result = resData.list
              }
            }
            xGridOpt.loading = false
            resolve({total, result})
          }

          /** 接口需要的参数 */
          const params = {
            name: trimValue(form.name),
            businessName: trimValue(form.businessName),
            serviceStatus: form.serviceStatus || undefined,
            maintenanceType: form.maintenanceType || undefined,
            type: form.type || undefined,
            vipLevel: form.vipLevel || undefined,
            size: page.pageSize,
            currentPage: page.currentPage
          }
          /** 调用接口 */
          getCustomerApi(params).then(callback).catch(callback)
        })
      },
      /** 导出全量数据时，会自动触发queryAll方法 */
      queryAll: ({form}) => {
        return new Promise<any>((resolve: Function) => {
          let total = 0
          let result: RowMeta[] = []
          /** 加载数据 */
          const callback = (res: CustomerTableData) => {
            if (res && res.data) {
              const resData = res.data
              // 总数
              if (Number.isInteger(resData.total)) {
                total = resData.total
              }
              // 处理数据
              if (Array.isArray(resData.list)) {
                result = resData.list
                resData.list.forEach(item => {
                  if (item.type === 1) {
                    item.type = "POC"
                  } else if (item.type === 2) {
                    item.type = "正式"
                  }

                  if (item.serviceStatus === 2) {
                    item.serviceStatus = "已过期"
                  } else if (item.serviceStatus === 1) {
                    item.serviceStatus = "维保中"
                  }
                })
              }
            }
            xGridOpt.loading = false
            resolve(result)
          }

          /** 接口需要的参数 */
          const params = {
            name: form.name || undefined,
            business: form.business || undefined,
            serviceStatus: form.serviceStatus || undefined,
            maintenanceType: form.maintenanceType || undefined,
            type: form.type || undefined,
            vipLevel: form.vipLevel || undefined
          }
          /** 调用接口 */
          getCustomerApi(params).then(callback).catch(callback)
        })
      }
    }
  }
})
//#endregion

//#region vxe-modal
const xModalDom = ref<VxeModalInstance>()
const xModalOpt: VxeModalProps = reactive({
  title: "",
  width: "700px",
  height: "600px",
  showClose: true,
  escClosable: true,
  maskClosable: false,
  beforeHideMethod: () => {
    xFormDom.value?.clearValidate()
    return Promise.resolve()
  }
})
//#endregion

//#region vxe-form
// 根据选择的客户类型决定是否显示维保有效期的输入框
const showServiceDateSelector: Ref<boolean> = computed(() => xFormOpt.data.type === 2)

// 根据维保有效期来决定是否显示维保类型(免费 or 付费)
const showMaintenanceType: Ref<boolean> = computed(() => {
  let endDate
  const sd = xFormOpt.data.serviceDate
  if (sd != undefined && typeof sd === "object" && Object.keys(sd).length === 2) {
    endDate = new Date(sd[1])
    const currentDate = new Date()
    if (endDate >= currentDate) {
      return true
    }
  }
  return false
})

const xFormDom = ref<VxeFormInstance>()
const xFormOpt = reactive<VxeFormProps>({
  span: 20,
  titleWidth: "30%",
  loading: false,
  /** 是否显示标题冒号 */
  titleColon: false,
  titleAlign: "right",
  /** 表单数据 */
  data: {
    id: "",
    name: "",
    type: "",
    businessID: "",
    serviceStatus: "",
    serviceDate: [],
    maintenanceType: "",
    description: ""
  },
  /** 项列表 */
  items: [
    {
      field: "name",
      title: "客户名称",
      itemRender: {
        name: "$input",
        props: {
          placeholder: "请输入",
          clearable: true
        }
      }
    },
    {
      field: "type",
      title: "客户类型",
      itemRender: {
        name: "$select",
        props: {
          placeholder: "请选择",
          options: [
            {value: 1, label: "POC客户"},
            {value: 2, label: "正式客户"}
          ],
          clearable: true
        }
      }
    },
    {
      field: "businessID",
      title: "商务",
      itemRender: {
        name: "$select",
        props: {
          placeholder: "请选择",
          options: peopleOptions,
          filterable: true
        }
      }
    },
    {
      field: "serviceDate",
      title: "维保日期",
      itemRender: {
        name: "ElDatePicker",
        props: {
          type: "daterange",
          valueFormat: "YYYY-MM-DD",
          startPlaceholder: "起始日期",
          endPlaceholder: "截止日期",
          unlinkPanels: true,
          clearable: true
        }
      },
      visibleMethod: () => showServiceDateSelector.value
    },
    {
      field: "maintenanceType",
      title: "维保类型",
      itemRender: {
        name: "$select",
        props: {
          placeholder: "请选择",
          options: [
            {value: 1, label: "付费"},
            {value: 2, label: "免费"}
          ],
          clearable: true
        }
      },
      visibleMethod: () => showMaintenanceType.value
    },
    {
      field: "vipLevel",
      title: "VIP 等级",
      itemRender: {
        name: "$select",
        props: {
          placeholder: "请选择",
          options: [
            {value: 1, label: "VIP1（维保合同小于5W）"},
            {value: 2, label: "VIP2（维保合同5W ~ 15W）"},
            {value: 3, label: "VIP3（维保合同大于15W）"},
            {value: 4, label: "VIP4（合同金额超过100W）"}
          ],
          clearable: true
        }
      },
      visibleMethod: () => showServiceDateSelector.value
    },
    {
      field: "description",
      title: "备注",
      itemRender: {
        name: "$textarea",
        props: {
          placeholder: "请输入",
          autosize: {minRows: 5, maxRows: 5},
          clearable: true
        }
      }
    },
    {
      align: "right",
      itemRender: {
        name: "$buttons",
        children: [
          {props: {content: "取消"}, events: {click: () => xModalDom.value?.close()}},
          {
            props: {type: "submit", content: "确定", status: "primary"},
            events: {click: () => crudStore.onSubmitForm()}
          }
        ]
      }
    }
  ],
  /** 校验规则 */
  rules: {
    name: [
      {
        required: true,
        validator: ({itemValue}) => {
          if (!itemValue) {
            return new Error("请输入")
          }
          if (!itemValue.trim()) {
            return new Error("空格无效")
          }
        }
      }
    ],
    serviceDate: [
      {
        required: true,
        validator: ({itemValue}) => {
          if (!itemValue) {
            return new Error("请选择正确的日期")
          }
          if (itemValue.length !== 2) {
            return new Error("请选择正确的日期")
          }
        }
      }
    ],
    type: [
      {
        required: true,
        validator: ({itemValue}) => {
          if (itemValue === "") {
            return new Error("请选择客户类型")
          }
        }
      }
    ],
    maintenanceType: [
      {
        required: true,
        validator: ({itemValue}) => {
          if (itemValue === "") {
            return new Error("请选择维保类型")
          }
        }
      }
    ]
  }
})
//#endregion

//#region CRUD
const crudStore = reactive({
  /** 表单类型：修改：true 新增：false */
  isUpdate: true,
  /** 加载表格数据 */
  commitQuery: () => xGridDom.value?.commitProxy("query"),
  /** 清空表格数据 */
  clearTable: () => xGridDom.value?.reloadData([]),
  /** 点击显示弹窗 */
  onShowModal: (row?: RowMeta) => {
    if (row) {
      crudStore.isUpdate = true
      xModalOpt.title = "修改客户信息"
      // 赋值
      xFormOpt.data.id = row.id
      xFormOpt.data.name = row.name
      xFormOpt.data.type = row.type
      xFormOpt.data.businessID = row.businessID !== 0 ? row.businessID : ""
      xFormOpt.data.description = row.description
      xFormOpt.data.serviceStatus = row.serviceStatus
      const startDate = formatDate(row.serviceStartDate)
      const endDate = formatDate(row.serviceEndDate)
      xFormOpt.data.serviceDate = []
      xFormOpt.data.serviceDate.push(startDate)
      xFormOpt.data.serviceDate.push(endDate)
      xFormOpt.data.vipLevel = row.vipLevel !== 10 ? row.vipLevel : ""
      xFormOpt.data.maintenanceType = row.maintenanceType !== 10 ? row.maintenanceType : ""
    } else {
      xFormOpt.data.id = 0
      crudStore.isUpdate = false
      xModalOpt.title = "新增客户信息"
    }
    xModalDom.value?.open()
    nextTick(() => {
      !crudStore.isUpdate && xFormDom.value?.reset()
      xFormDom.value?.clearValidate()
    })
  },
  /** 确定并保存 */
  onSubmitForm: () => {
    if (xFormOpt.loading) return
    xFormDom.value?.validate(async (errMap?: VxeFormDefines.ValidateErrorMapParams) => {
      if (errMap) return
      xFormOpt.loading = true
      const callback = (err?: any) => {
        xFormOpt.loading = false
        if (err) return
        xModalDom.value?.close()
        !crudStore.isUpdate && crudStore.afterInsert()
        crudStore.commitQuery()
      }
      try {
        let startDate = ""
        let endDate = ""
        if (typeof xFormOpt.data.serviceDate === "object" && Object.keys(xFormOpt.data.serviceDate).length === 2) {
          startDate = xFormOpt.data.serviceDate[0]
          endDate = xFormOpt.data.serviceDate[1]
        }

        let apiFunction
        if (crudStore.isUpdate) {
          apiFunction = updateCustomerApi
        } else {
          apiFunction = addCustomerApi
        }
        const mt = showMaintenanceType.value === true ? xFormOpt.data.maintenanceType : 10

        const res = await apiFunction({
          id: xFormOpt.data.id,
          name: xFormOpt.data.name,
          type: xFormOpt.data.type,
          businessID: xFormOpt.data.businessID,
          serviceStatus: xFormOpt.data.serviceStatus,
          description: xFormOpt.data.description,
          serviceStartDate: startDate,
          vipLevel: xFormOpt.data.vipLevel || undefined,
          serviceEndDate: endDate,
          maintenanceType: mt
        })

        ElMessage({type: "success", message: res.msg})
      } catch (error) {
        console.log(error)
      } finally {
        callback()
      }
    })
  },

  /** 新增后是否跳入最后一页 */
  afterInsert: () => {
    const pager: VxeGridPropTypes.ProxyAjaxQueryPageParams | undefined = xGridDom.value?.getProxyInfo()?.pager
    if (pager) {
      const currTotal: number = pager.currentPage * pager.pageSize
      if (currTotal === pager.total) {
        ++pager.currentPage
      }
    }
  },
  /** 删除 */
  onDelete: (row: RowMeta) => {
    let tip = `该操作会同时删除该客户的环境、license以及事件。</br>`
    tip += `是否确定 <strong style="color:red;">删除</strong> 客户 <strong style="color:#409eff;">${row.name}</strong> ？`

    const config: ElMessageBoxOptions = {
      type: "warning",
      showClose: true,
      closeOnClickModal: true,
      closeOnPressEscape: true,
      cancelButtonText: "取消",
      confirmButtonText: "确定",
      dangerouslyUseHTMLString: true
    }
    ElMessageBox.confirm(tip, "提示", config)
      .then(() => {
        deleteCustomerApi(row.id)
          .then(() => {
            ElMessage.success("删除成功")
            crudStore.afterDelete()
            crudStore.commitQuery()
          })
          .catch(() => 1)
      })
      .catch(() => 1)
  },
  /** 删除后是否返回上一页 */
  afterDelete: () => {
    const tableData: RowMeta[] = xGridDom.value!.getData()
    const pager: VxeGridPropTypes.ProxyAjaxQueryPageParams | undefined = xGridDom.value?.getProxyInfo()?.pager
    if (pager && pager.currentPage > 1 && tableData.length === 1) {
      --pager.currentPage
    }
  }
})
//#endregion
</script>

<style lang="scss" scoped>
.expand-wrapper {
  padding: 10px;
}

.tooltip-content {
  white-space: pre-wrap; /* 或者使用 pre-line */
  word-break: break-all; /* 根据需要使用 word-break 属性 */
}
</style>
